﻿using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;

namespace TKC.Scripts.Test.Editor
{
    public class SceneViewRectTranformEditor 
    {

        [InitializeOnLoadMethod]
        static void Register()
        {
            SceneView.duringSceneGui += OnSceneGUI;
        }
        private static void OnSceneGUI(SceneView sceneView)
        {
            if(!sceneView.in2DMode)
                return;
            Event e = Event.current;
            if (e.type == EventType.KeyDown)
            {
                if( e.keyCode == KeyCode.UpArrow)
                    MoveDir(0,1);
                if( e.keyCode == KeyCode.DownArrow)
                    MoveDir(0,-1);
                if( e.keyCode == KeyCode.LeftArrow)
                    MoveDir(-1,0);
                if( e.keyCode == KeyCode.RightArrow)
                    MoveDir(1,0);
            }
        }

        static void MoveDir(int dirx,int diry)
        {
            Event.current.Use();
            List<Transform> list = Selection.objects.Where(f => f is GameObject)
                .Select(g => (g as GameObject).transform).ToList();
            var moves = list.Where(s => !IsParentInList(s, list)).ToList();
            foreach (Transform transform in moves)
            {
                transform.GetComponent<RectTransform>().anchoredPosition += new Vector2(dirx, diry);
            }
        }

        static bool IsParentInList(Transform transform,List<Transform> list)
        {
            Transform parent = transform.parent;
            while (parent)
            {
                if (list.Contains(parent)) return true;
                parent = parent.parent;
            }
            return false;
        }
    }
}